﻿using RestSharp;

namespace BlueWePush.Service.BaseService
{
    /// <summary>
    /// 请求封装
    /// </summary>
    public class RestClientWrapper
    {
        private readonly RestClient _client;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseUrl"></param>
        public RestClientWrapper(string baseUrl)
        {
            _client = new RestClient(new RestClientOptions(baseUrl)
            {
                Timeout = TimeSpan.FromSeconds(5)
            });
        }

        /// <summary>
        /// 通用 GET 请求
        /// </summary>
        /// <typeparam name="T">数据结构</typeparam>
        /// <param name="endpoint">API方法名</param>
        /// <param name="queryParams">参数</param>
        /// <param name="headers">标头</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public T GetRequest<T>(string endpoint = null, Dictionary<string, string> queryParams = null, Dictionary<string, string> headers = null)
        {
            var request = new RestRequest(endpoint, Method.Get);

            // 添加查询参数
            if (queryParams != null)
            {
                foreach (var query in queryParams)
                {
                    request.AddParameter(query.Key, query.Value);
                }
            }

            // 添加 Headers
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }

            var response = _client.Execute<T>(request);

            if (!response.IsSuccessStatusCode)
            {
                return default;
            }

            return response.Data;
        }

        /// <summary>
        /// 通用 POST 请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="endpoint"></param>
        /// <param name="body"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public T PostRequest<T>(string endpoint = null, object body = null, Dictionary<string, string> headers = null)
        {
            var request = new RestRequest(endpoint, Method.Post);

            // 添加 Body
            if (body != null)
            {
                request.AddJsonBody(body);
            }

            // 添加 Headers
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }

            var response = _client.Execute<T>(request);

            if (!response.IsSuccessStatusCode)
            {
                return default;
            }

            return response.Data;
        }
    }
}